package cn.lili.modules.store.serviceimpl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.lili.cache.Cache;
import cn.lili.cache.CachePrefix;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.SceneEnums;
import cn.lili.common.utils.BeanUtil;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.utils.SnowFlake;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.exchange.AmqpExchangeProperties;
import cn.lili.modules.distribution.entity.vos.HomeResult;
import cn.lili.modules.goods.client.CategoryClient;
import cn.lili.modules.goods.client.GoodsClient;
import cn.lili.modules.goods.entity.dos.Category;
import cn.lili.modules.member.entity.dos.User;
import cn.lili.modules.member.entity.dto.CollectionDTO;
import cn.lili.modules.member.entity.dto.UserInfoDTO;
import cn.lili.modules.member.service.UserService;
import cn.lili.modules.message.entity.dos.Message;
import cn.lili.modules.message.entity.enums.MessageSendClient;
import cn.lili.modules.message.entity.enums.RangeEnum;
import cn.lili.modules.operationcenter.client.OperationCenterClient;
import cn.lili.modules.operationcenter.entity.dos.OperationCenter;
import cn.lili.modules.payment.client.PaymentClient;
import cn.lili.modules.payment.entity.dto.UrbanSubstationCommissionParams;
import cn.lili.modules.payment.entity.enums.PaymentMethodEnum;
import cn.lili.modules.search.utils.EsIndexUtil;
import cn.lili.modules.statistics.entity.enums.SearchTypeEnum;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.entity.enums.StoreSceneEnum;
import cn.lili.modules.supplier.entity.dos.SupplierAuditRecord;
import cn.lili.modules.store.entity.dto.*;
import cn.lili.modules.store.entity.enums.StoreStatusEnum;
import cn.lili.modules.store.entity.enums.SupplierAuditEnum;
import cn.lili.modules.store.entity.vos.StoreBasicInfoVO;
import cn.lili.modules.store.entity.vos.StoreLicenceVO;
import cn.lili.modules.store.entity.vos.StoreManagementCategoryVO;
import cn.lili.modules.store.entity.vos.StoreVO;
import cn.lili.modules.store.mapper.StoreMapper;
import cn.lili.modules.store.service.StoreService;
import cn.lili.modules.store.service.SupplierAuditRecordService;
import cn.lili.modules.system.client.IRegionClient;
import cn.lili.modules.system.client.SettingClient;
import cn.lili.modules.system.entity.dos.Region;
import cn.lili.modules.system.entity.dos.Setting;
import cn.lili.modules.system.entity.dto.UrbanSubstationAuditSetting;
import cn.lili.modules.urbansubstation.client.UrbanSubstationClient;
import cn.lili.modules.urbansubstation.entity.dos.UrbanSubstation;
import cn.lili.modules.urbansubstation.entity.dto.UrbanSubstationSearchPageParams;
import cn.lili.modules.urbansubstation.entity.dto.UrbanSubstationSearchParams;
import cn.lili.modules.urbansubstation.entity.vos.UrbanSubstationVo;
import cn.lili.mybatis.util.PageUtil;
import cn.lili.routing.GoodsRoutingKey;
import cn.lili.util.AmqpMessage;
import cn.lili.util.AmqpSender;
import cn.lili.util.HomeResultUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 店铺业务层实现
 *
 * @author pikachu
 * @since 2020-03-07 16:18:56
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements StoreService {

    /**
     * 会员
     */
    private final UserService userService;

    private final CategoryClient categoryClient;

    private final GoodsClient goodsClient;

    private final Cache cache;

    private final AmqpSender amqpSender;

    private final AmqpExchangeProperties amqpExchangeProperties;

    @Lazy
    private final UrbanSubstationClient urbanSubstationClient;

    private final SupplierAuditRecordService supplierAuditRecordService;

    private final SettingClient settingClient;

    private final PaymentClient paymentClient;

    private final RedissonClient redissonClient;

    private final OperationCenterClient operationCenterClient;

    private final IRegionClient regionClient;


    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public Store add(StoreApplyDTO storeApplyDTO) {

        //判断店铺名称是否存在
        LambdaQueryWrapper<Store> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Store::getStoreName, storeApplyDTO.getStoreName());
        List<Store> list = this.list(queryWrapper);
        if (ObjectUtil.isNotNull(list) && !list.isEmpty()) {
            throw new ServiceException(ResultCode.STORE_NAME_EXIST_ERROR);
        }

        //添加店铺
        Store store = new Store(storeApplyDTO);
        store.setId(SnowFlake.getIdStr());
        store.setExtendId(store.getId());
        AuthUser authUser = UserContext.getCurrentUser();
        store.setEnterId(authUser != null ? authUser.getId() : null);

        User user = userService.registerHandler(UserInfoDTO.builder()
                .username(storeApplyDTO.getUsername())
                .password(new BCryptPasswordEncoder().encode(storeApplyDTO.getPassword()))
                .mobile(storeApplyDTO.getMobile())
                .extendName(storeApplyDTO.getStoreName())
                .nickName("用户" + storeApplyDTO.getMobile())
                .scene(SceneEnums.valueOf(storeApplyDTO.getScene()))
                .extendId(store.getId())
                .urbanSubstationId(CharSequenceUtil.isNotEmpty(store.getUrbanUserId()) ? store.getUrbanUserId() : null)
                .isSuper(true)
                .shopkeeper(true)
                .build());

        store.setManagerId(user.getId());
        if (storeApplyDTO.getIsFree() != null) {
            store.setIsFree(storeApplyDTO.getIsFree());
        }

        if (this.save(store)) {
            // 有城市分站ID表示供应商
            /*if (CharSequenceUtil.isNotEmpty(storeApplyDTO.getUrbanUserId())) {
                Setting setting = settingClient.get("URBANSUBSTATION_AUDIT_SETTING");
                UrbanSubstationAuditSetting urbanSubstationAuditSetting = JSONUtil.toBean(setting.getSettingValue(), UrbanSubstationAuditSetting.class);
                // 保存供应商审核数据
                SupplierAuditRecord supplierAuditRecord = new SupplierAuditRecord(store.getId(), storeApplyDTO.getUrbanUserId(), urbanSubstationAuditSetting.getAuditFailCount());
                supplierAuditRecordService.save(supplierAuditRecord);
            }*/
        }
        return store;
    }

    @Override
    public Page<StoreVO> findByConditionPage(StoreSearchParams storeSearchParams, PageVO page) {
        QueryWrapper queryWrapper = storeSearchParams.queryWrapper();
        if (CharSequenceUtil.isNotEmpty(storeSearchParams.getScene()) &&
                (SceneEnums.URBAN_SUBSTATION.equals(Objects.requireNonNull(UserContext.getCurrentUser()).getScene()))) {
            List<Store> storeList = getSupplierListByUrbanId(UserContext.getCurrentUser().getId());
            if (!storeList.isEmpty()) {
                List<String> extList = storeList.stream().map(Store::getId).collect(Collectors.toList());
                queryWrapper.in("id", extList);
            }else {
                queryWrapper.eq("id", "");
            }
        }
        Page<StoreVO> p = this.baseMapper.getStoreList(PageUtil.initPage(page), queryWrapper);
        if(!p.getRecords().isEmpty()) {
            p.getRecords().stream()
                    .filter(storeVO -> StoreStatusEnum.APPLYING.name().equals(storeVO.getStoreStatus()))
                    .forEach(storeVO -> {
                User user = userService.getByExtId(storeVO.getId());
                if (null != user && user.getAuditStatus() == 0) {
                    storeVO.setAuditFlag(0);
                }else {
                    storeVO.setAuditFlag(user.getAuditStatus());
                }
            });
        }
        return p;
    }


    /**
     * 列表查询
     *
     * @param searchParams 查询参数
     * @return 店铺列表
     */
    @Override
    public List<Store> list(StoreSearchParams searchParams) {
        return this.list(searchParams.queryWrapper());
    }


    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public Store edit(StoreEditDTO storeEditDTO) {
        if (storeEditDTO != null) {
            //判断店铺名是否唯一
            QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("store_name", storeEditDTO.getStoreName());
            List<Store> list = this.list(queryWrapper);
            //如果店铺名存在，判断是否是当前店铺
            if (ObjectUtil.isNotNull(list) && !list.isEmpty()) {
                list.forEach(store -> {
                    if (!store.getId().equals(storeEditDTO.getStoreId())) {
                        throw new ServiceException(ResultCode.STORE_NAME_EXIST_ERROR);
                    }
                });
            }

            Store store = this.getById(storeEditDTO.getStoreId());
            if (store != null) {
                BeanUtil.copyProperties(storeEditDTO, store);
                store.setId(storeEditDTO.getStoreId());
                store.setBusinessCategoryArray(storeEditDTO.getBusinessCategory());
                if (StoreStatusEnum.REFUSED.name().equals(store.getStoreStatus())) {
                    store.setStoreStatus(StoreStatusEnum.APPLYING.name());
                }
                if (storeEditDTO.getIsFree() != null) {
                    store.setIsFree(storeEditDTO.getIsFree());
                }
                boolean result = this.updateById(store);
                if (result) {
                    this.updateStoreGoodsInfo(store);
                }
            }
            if (store!=null && StringUtils.isNotBlank(store.getUrbanUserId())) {
                UrbanSubstation urbanSubstation = urbanSubstationClient.getById(store.getUrbanUserId());
                store.setUrbanUserName(urbanSubstation != null ? urbanSubstation.getUrbanName() : null);
            }
            cache.remove(CachePrefix.STORE.getPrefix() + storeEditDTO.getStoreId());
            return store;
        } else {
            throw new ServiceException(ResultCode.STORE_NOT_EXIST);
        }
    }

    @Override
    public Store customAdd(Store store) {
        this.save(store);
        return store;
    }

    @Override
    public Store customEdit(Store store) {
        this.updateById(store);
        return this.getById(store.getId());
    }


    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void audit(String id, Boolean passed, String rejectReason) {
        Store store = this.getById(id);
        if (store == null) {
            throw new ServiceException(ResultCode.STORE_NOT_EXIST);
        }
        User user = userService.getByExtId(id);
        if (Boolean.TRUE.equals(passed)) {
            // 审核供应商
            if (store.getScene().equals(SceneEnums.SUPPLIER.name())) {
                // 平台审核-直接审核通过
                if (SceneEnums.MANAGER.equals(Objects.requireNonNull(UserContext.getCurrentUser()).getScene())) {
                    if (null != user) {
                        user.setAuditStatus(2);
                        userService.updateById(user);
                    }
                    store.setStoreStatus(StoreStatusEnum.OPEN.value());
                }else { // 城市分站审核-审核通过后还需要平台审核
                    store.setStoreStatus(StoreStatusEnum.APPLYING.value());
                    if (null != user) {
                        user.setAuditStatus(1);
                        userService.updateById(user);
                    }
                }
            }else {
                store.setStoreStatus(StoreStatusEnum.OPEN.value());
            }
        } else {
            if (null != user) {
                user.setAuditStatus(2);
                userService.updateById(user);
            }
            if (CharSequenceUtil.isNotEmpty(rejectReason)) {
                store.setRejectReason(rejectReason);
            }
            store.setStoreStatus(StoreStatusEnum.REFUSED.value());
        }

        cache.remove(CachePrefix.STORE.getPrefix() + id);
        this.updateById(store);
    }

    @Override
    public void disable(String id) {
        Store store = this.getById(id);
        if (store != null) {
            store.setStoreStatus(StoreStatusEnum.CLOSED.value());

            //下架所有此店铺商品
            goodsClient.underStoreGoods(id);
            this.updateById(store);
            cache.remove(CachePrefix.STORE.getPrefix() + id);
            Message message = new Message();
            message.setMessageRange(RangeEnum.APPOINT.name());
            message.setMessageClient(MessageSendClient.STORE.name());

            return;
        }

        throw new ServiceException(ResultCode.STORE_NOT_EXIST);
    }

    @Override
    public void enable(String id) {
        Store store = this.getById(id);
        if (store != null) {
            store.setStoreStatus(StoreStatusEnum.OPEN.value());
            this.updateById(store);
            cache.remove(CachePrefix.STORE.getPrefix() + id);
            return;
        }
        throw new ServiceException(ResultCode.STORE_NOT_EXIST);
    }

    @Override
    public void updateStoreGoodsNum(String storeId, Long num) {
        //修改店铺商品数量
        this.update(new LambdaUpdateWrapper<Store>()
                .set(Store::getGoodsNum, num)
                .eq(Store::getId, storeId));
        cache.remove(CachePrefix.STORE.getPrefix() + storeId);
    }

    @Override
    public void updateStoreCollectionNum(CollectionDTO collectionDTO) {
        baseMapper.updateCollection(collectionDTO.getId(), collectionDTO.getNum());
        cache.remove(CachePrefix.STORE.getPrefix() + collectionDTO.getId());
    }

    /**
     * 更新评分
     *
     * @param storeId          店铺ID
     * @param deliveryScore    物流评分
     * @param serviceScore     服务评分
     * @param descriptionScore 描述评分
     */
    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void updateScore(String storeId, String deliveryScore, String serviceScore, String descriptionScore) {
        LambdaUpdateWrapper<Store> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
        lambdaUpdateWrapper.eq(Store::getId, storeId);
        lambdaUpdateWrapper.set(Store::getDescriptionScore, descriptionScore);
        lambdaUpdateWrapper.set(Store::getDeliveryScore, deliveryScore);
        lambdaUpdateWrapper.set(Store::getServiceScore, serviceScore);
        this.update(lambdaUpdateWrapper);
    }

    @Override
    public StoreVO getStoreDetailVO(String storeId) {
        StoreVO storeVO = (StoreVO) cache.get(CachePrefix.STORE.getPrefix() + storeId);
        if (storeVO == null) {
            storeVO = this.baseMapper.getStoreVO(storeId);
            cache.put(CachePrefix.STORE.getPrefix() + storeId, storeVO, 7200L);
        }
        User user = userService.getByExtId(storeVO.getId());
        if (null != user && user.getAuditStatus() == 0) {
            storeVO.setAuditFlag(0);
        }else {
            storeVO.setAuditFlag(user.getAuditStatus());
        }

        if (CharSequenceUtil.isNotEmpty(storeVO.getUrbanUserId())) {
            User user1 = userService.getById(storeVO.getUrbanUserId());
            if (null != user1) {
                UrbanSubstation urbanSubstation = urbanSubstationClient.getById(user1.getExtendId());
                if (null != urbanSubstation) {
                    storeVO.setUrbanName(urbanSubstation.getUrbanName());
                }
            }
        }
        return storeVO;
    }

    @Override
    public Store getStoreDetailBySceneAndUserId(String extendId, SceneEnums scene) {
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Store::getExtendId, extendId);
        queryWrapper.eq(Store::getScene, scene.value());
        return this.getOne(queryWrapper, false);
    }

    @Override
    public Store getStoreByManagerId(String managerId, SceneEnums scene) {
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Store::getManagerId, managerId);
        queryWrapper.eq(Store::getScene, scene.value());
        return this.getOne(queryWrapper, false);
    }

    @Override
    public Boolean editStoreSetting(StoreSettingDTO storeSettingDTO) {
        AuthUser tokenUser = Objects.requireNonNull(UserContext.getCurrentUser());
        //修改店铺
        Store store = this.getById(tokenUser.getExtendId());
        BeanUtil.copyProperties(storeSettingDTO, store);
        this.updateById(store);
        this.updateStoreGoodsInfo(store);
        return true;
    }

    @Override
    public void updateStoreGoodsInfo(Store store) {
        goodsClient.updateStoreDetail(store);
        Map<String, Object> updateIndexFieldsMap = EsIndexUtil.getUpdateIndexFieldsMap(
                MapUtil.builder(new HashMap<String, Object>()).put("storeId", store.getId()).build(),
                MapUtil.builder(new HashMap<String, Object>()).put("storeName", store.getStoreName())
                        .put("selfOperated", store.getSelfOperated()).build());
        amqpSender.send(AmqpMessage.builder()
                .exchange(amqpExchangeProperties.getGoods())
                .routingKey(GoodsRoutingKey.UPDATE_GOODS_INDEX_FIELD)
                .message(JSONObject.toJSONString(updateIndexFieldsMap))
                .build());
    }


    @Override
    public StoreBasicInfoVO getStoreBasicInfoDTO(String storeId) {
        StoreVO storeVO = this.getStoreDetailVO(storeId);
        StoreBasicInfoVO storeBasicInfoVO = new StoreBasicInfoVO();
        BeanUtils.copyProperties(storeVO, storeBasicInfoVO);
        return storeBasicInfoVO;
    }

    @Override
    public List<StoreManagementCategoryVO> goodsManagementCategory(String storeId) {

        //获取顶部分类列表
        List<Category> categoryList = categoryClient.firstCategory();

        //获取店铺分类
        String[] storeCategoryList = this.getById(storeId).getBusinessCategory().split(",");
        List<StoreManagementCategoryVO> list = new ArrayList<>();
        for (Category category : categoryList) {
            StoreManagementCategoryVO storeManagementCategoryVO = new StoreManagementCategoryVO(category);
            for (String storeCategory : storeCategoryList) {
                if (storeCategory.equals(category.getId())) {
                    storeManagementCategoryVO.setSelected(true);
                }
            }
            list.add(storeManagementCategoryVO);
        }
        return list;
    }

    @Override
    public StoreLicenceVO getStoreLicenceVO(String storeId) {
        StoreLicenceVO storeLicenceVO = new StoreLicenceVO();
        Store store = this.getById(storeId);
        BeanUtils.copyProperties(store, storeLicenceVO);
        return storeLicenceVO;
    }


    @Override
    public void ownerEdit(StoreOwnerEditDTO storeOwnerEditDTO) {
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        if (UserContext.getCurrentUser() != null) {
            SceneEnums scene = Objects.requireNonNull(UserContext.getCurrentUser()).getScene();
            if (scene.equals(SceneEnums.STORE) || scene.equals(SceneEnums.SUPPLIER)) {
                queryWrapper.eq("id", UserContext.getCurrentUser().getExtendId());
                queryWrapper.eq("scene", UserContext.getCurrentUser().getScene().value());
            } else {
                return;
            }
        }
        Store store = this.getOne(queryWrapper);

        if (store == null) {
            throw new ServiceException(ResultCode.STORE_NOT_EXIST);
        }

        BeanUtils.copyProperties(storeOwnerEditDTO, store);

        this.updateById(store);
        this.updateStoreGoodsInfo(store);
        this.removeCache(store.getId());
    }


    /**
     * 删除缓存
     *
     * @param storeId 店铺id
     */
    private void removeCache(String storeId) {
        cache.remove(CachePrefix.STORE.getPrefix() + storeId);
    }


    public List<Store> getSupplierListByUrbanId(String urbanId) {
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Store::getUrbanUserId, urbanId);
        queryWrapper.eq(Store::getScene, SceneEnums.SUPPLIER.name());
        List<Store> storeList = this.baseMapper.selectList(queryWrapper);
        return storeList;
    }


    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void auditSupplier(String id, Boolean passed, String rejectReason, String status) {
        Store store = this.getById(id);
        if (store == null) {
            throw new ServiceException(ResultCode.STORE_NOT_EXIST);
        }
        // 供应商未打款，不能审核
        if (status.equals(StoreStatusEnum.NONPAYMENT.name())) {
            throw new ServiceException(ResultCode.STORE_STATUS_NONPAYMENT_ERROR);
        }
        User user = userService.getByExtId(id);
        SupplierAuditRecord supplierAuditRecord = supplierAuditRecordService.getBySupplierId(id);
        if (Boolean.TRUE.equals(passed)) {
            // 审核中
            if (status.equals(StoreStatusEnum.APPLYING.name())) {
                // 平台审核-直接审核通过到未打款状态
                if (SceneEnums.MANAGER.equals(Objects.requireNonNull(UserContext.getCurrentUser()).getScene())) {
                    RLock rLock = redissonClient.getLock(id);
                    try {
                        rLock.lock();
                        if (null != supplierAuditRecord) {
                            supplierAuditRecord.setPlatformVerify(true);
                            // 供应商已付款
                            if (SupplierAuditEnum.PAID.name().equals(supplierAuditRecord.getPaymentStatus())) {
                                // 打款给城市分站
                                UrbanSubstation urbanSubstation = urbanSubstationClient.getUrbanSubstation(store.getUrbanUserId());
                                if (null != urbanSubstation) {
                                    Setting setting = settingClient.get("URBANSUBSTATION_AUDIT_SETTING");
                                    UrbanSubstationAuditSetting urbanSubstationAuditSetting = JSONUtil.toBean(setting.getSettingValue(), UrbanSubstationAuditSetting.class);
                                    UrbanSubstationCommissionParams params = new UrbanSubstationCommissionParams();
                                    params.setPayeeId(urbanSubstation.getId());
                                    long count = getSupplierCountByUrbanId(store.getUrbanUserId());
                                    if (count > urbanSubstationAuditSetting.getSiteLevelCount()) {
                                        params.setPrice(Double.valueOf(urbanSubstationAuditSetting.getSiteLevelMoreThan()));
                                    }else {
                                        params.setPrice(Double.valueOf(urbanSubstationAuditSetting.getSiteLevelBelow()));
                                    }
                                    params.setPaymentId(store.getId());
                                    params.setPaymentMethodEnum(PaymentMethodEnum.WALLET);
                                    paymentClient.urbanSubstationCommission(params);
                                }
                            }
                            supplierAuditRecordService.updateById(supplierAuditRecord);
                        }
                        store.setStoreStatus(StoreStatusEnum.NONPAYMENT.value());
                    }catch (Exception e) {
                        e.printStackTrace();
                    }finally {
                        rLock.unlock();
                    }
                }else { // 城市分站审核-审核通过后还需要平台审核
                    store.setStoreStatus(StoreStatusEnum.APPLYING.value());
                    if (null != supplierAuditRecord) {
                        supplierAuditRecord.setSiteVerify(true);
                        supplierAuditRecordService.updateById(supplierAuditRecord);
                    }
                }
                if (null != user) {
                    user.setAuditStatus(1);
                    userService.updateById(user);
                }
            }else if (status.equals(StoreStatusEnum.PAIDAPPLYING.name())) {
                // 审核已打款数据-只有平台才能审核
                if (!SceneEnums.MANAGER.equals(Objects.requireNonNull(UserContext.getCurrentUser()).getScene())) {
                    throw new ServiceException(ResultCode.USER_AUTHORITY_ERROR);
                }
                if (null != user) {
                    user.setAuditStatus(2);
                    userService.updateById(user);
                }
                store.setStoreStatus(StoreStatusEnum.OPEN.value());
            }
        } else {
            if (status.equals(StoreStatusEnum.APPLYING.name())) {
                store.setStoreStatus(StoreStatusEnum.REFUSED.value());
                if (null != supplierAuditRecord) {
                    Integer auditCount = supplierAuditRecord.getResidueAuditCount() - 1;
                    if (auditCount <= 0) {
                        auditCount = 0;
                        store.setStoreStatus(StoreStatusEnum.RESETAUDIT.value());
                    }
                    supplierAuditRecord.setResidueAuditCount(auditCount);
                }
            }else if (status.equals(StoreStatusEnum.PAIDAPPLYING.name())) {
                // 审核已打款数据-只有平台才能审核
                if (!SceneEnums.MANAGER.equals(Objects.requireNonNull(UserContext.getCurrentUser()).getScene())) {
                    throw new ServiceException(ResultCode.USER_AUTHORITY_ERROR);
                }
                store.setStoreStatus(StoreStatusEnum.PAIDAREFUSED.value());
            }
            if (null != user) {
                user.setAuditStatus(2);
                userService.updateById(user);
            }

            if (null != supplierAuditRecord) {
                if (SceneEnums.MANAGER.equals(Objects.requireNonNull(UserContext.getCurrentUser()).getScene())) {
                    supplierAuditRecord.setPlatformVerify(false);
                }else {
                    supplierAuditRecord.setSiteVerify(false);
                }
                supplierAuditRecordService.updateById(supplierAuditRecord);
            }

            if (CharSequenceUtil.isNotEmpty(rejectReason)) {
                store.setRejectReason(rejectReason);
            }
        }
        cache.remove(CachePrefix.STORE.getPrefix() + id);
        this.updateById(store);
    }


    /**
     * 根据城市分站ID获取城市分站下供应商数量
     * @param urbanId
     * @return
     */
    public long getSupplierCountByUrbanId (String urbanId) {
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Store::getUrbanUserId, urbanId);
        return this.baseMapper.selectCount(queryWrapper);
    }


    @Override
    public ResultMessage<List<UrbanSubstationVo>> getUrbanAndStoreList() {
        List<UrbanSubstation> substationList = urbanSubstationClient.select();
        if (CollectionUtil.isEmpty(substationList)) {
            return new ResultMessage<>();
        }
        List<UrbanSubstationVo> urbanSubstationVos = cn.hutool.core.bean.BeanUtil.copyToList(substationList, UrbanSubstationVo.class);
//        List<String> urbanIdList = urbanSubstationVos.stream().map(UrbanSubstationVo::getId).toList();

        LambdaQueryWrapper<Store> storeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        storeLambdaQueryWrapper.select(Store::getId, Store::getUrbanUserId, Store::getStoreName);
//        storeLambdaQueryWrapper.in(Store::getUrbanUserId, urbanIdList);
        List<Store> storeList = super.list(storeLambdaQueryWrapper);
        if (CollectionUtil.isEmpty(storeList)) {
            return ResultUtil.data(urbanSubstationVos);
        }

        Map<String, List<Store>> listMap = storeList.stream().filter(f -> StringUtils.isNotEmpty(f.getUrbanUserId())).collect(Collectors.groupingBy(Store::getUrbanUserId));
        for (UrbanSubstationVo urbanSubstationVo : urbanSubstationVos) {
            for (Map.Entry<String, List<Store>> entry : listMap.entrySet()) {
                if (urbanSubstationVo.getUserId().equals(entry.getKey())) {
                    urbanSubstationVo.setStoreList(entry.getValue());
                }
            }
        }
        return ResultUtil.data(urbanSubstationVos);
    }

    /**
     * 统计供应商新增多少家
     */
    @Override
    public ResultMessage<HomeResult> countingSupplierAdditions() {
        //创建默认值
        HomeResult homeResult = HomeResultUtil.createDefaultValue();
        //获取店铺
        List<Store> storeList = this.getStoreList();
        log.info("storeList == {}", JSONObject.toJSONString(storeList));
        if (CollectionUtil.isEmpty(storeList)) {
            return ResultUtil.data(homeResult);
        }
        //计算返回值
        homeResult = HomeResultUtil.createResult(storeList, store -> {
            Date createDate = store.getCreateTime();
            return createDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        });
        return ResultUtil.data(homeResult);
    }

    /**
     *
     * 获取当前运营中心省份operation_center --》  获取当前省份下的市区 region  --》 获取下的城市站点 urban_substation --》 获取店铺供应商 store
     * 获取运营中心下面的供应商
     * @return
     */
    @Override
    public List<Store> getStoreList() {
        //获取运行中心省份id
        AuthUser authUser = UserContext.getCurrentUser();
        if (authUser == null) {
            throw new ServiceException("请先登录后重试");
        }
        //获取当前运营中心省份operation_center
        OperationCenter operationCenter = operationCenterClient.getOperationCenter(authUser.getId());
        if (operationCenter == null) {
            throw new ServiceException("未获取到，运营中心信息");
        }
        //获取当前省份下的市区 region
        List<Region> regionList = regionClient.getRegionByParentId(operationCenter.getProvinceId());
        if (CollectionUtil.isEmpty(regionList)) {
            return new ArrayList<>();
        }
        List<String> regionIdList = regionList.stream().map(Region::getId).toList();
        log.info("regionList == {}", JSONObject.toJSONString(regionList));
        //获取下的城市站点 urban_substation
        UrbanSubstationSearchParams urbanSubstationSearchParams = new UrbanSubstationSearchParams();
        urbanSubstationSearchParams.setRegionList(regionIdList);
        PageVO pageVO = new PageVO();
        pageVO.setPageNumber(1);
        pageVO.setPageSize(100);
        UrbanSubstationSearchPageParams searchPageParams = new UrbanSubstationSearchPageParams();
        searchPageParams.setUrbanSubstationSearchParams(urbanSubstationSearchParams);
        searchPageParams.setPage(pageVO);
        Page<UrbanSubstation> urbanSubstationPage = urbanSubstationClient.getByRegionIds(searchPageParams);
        log.info("urbanSubstationPage == {}", JSONObject.toJSONString(urbanSubstationPage.getRecords()));
        if (CollectionUtil.isEmpty(urbanSubstationPage.getRecords())) {
            return new ArrayList<>();
        }
        //获取店铺供应商 store
        List<String> urbanSubstation = urbanSubstationPage.getRecords().stream().map(UrbanSubstation::getUserId).toList();
        LambdaQueryWrapper<Store> storeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        storeLambdaQueryWrapper.in(Store::getUrbanUserId, urbanSubstation);
        storeLambdaQueryWrapper.eq(Store::getScene, StoreSceneEnum.SUPPLIER.name());
        storeLambdaQueryWrapper.select(Store::getId, Store::getCreateTime);
        return super.list(storeLambdaQueryWrapper);
    }

    /**
     * 根据城市分站获取本月新增供应商数量
     * @param urbanId
     * @return
     */
    @Override
    public Long getCurrentMonthSupplierCountByUrbanId(String urbanId) {
        return this.baseMapper.getCurrentMonthSupplierCountByUrbanId(urbanId);
    }

    @Override
    public Long getSupplierListByParams(String urbanId, Date startTime, Date endTime) {
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Store::getUrbanUserId, urbanId);
        queryWrapper.eq(Store::getScene, SceneEnums.SUPPLIER.name());
        if (null != startTime && null != endTime) {
            queryWrapper.between(Store::getCreateTime, startTime, endTime);
        }
        return this.baseMapper.selectCount(queryWrapper);
    }

    public List<Store> getSupplierCount(String urbanId) {
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Store::getUrbanUserId, urbanId);
        queryWrapper.eq(Store::getScene, SceneEnums.SUPPLIER.name());
        List<Store> storeList = this.baseMapper.selectList(queryWrapper);
        return storeList;
    }
}